package com.frame.work.frame.deal.gateway;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.frame.work.common.util.HttpUtils;
import com.frame.work.entity.TblGateway;
import com.frame.work.mapper.TblGatewayMapper;
import com.frame.work.mqtt.Topic;
import com.frame.work.mqtt.data.handle.MqttDataHandle;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

/**
 * 网关信息上报操作类
 * 1：登陆
 * 2：心跳
 *
 * @author Administrator
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class GateWayFrameDeal {

    private final TblGatewayMapper tblGatewayMapper;
    private final MqttDataHandle mqttDataHandle;
    private static final String IGNORE_START = "192.168";

    public boolean loginDeal(String gatewayMac, String data, String clientIp) {
        //硬件版本号
        String hardwareVersionNumberStr = data.substring(data.length() - 8, data.length() - 0);
        String hardwareVersionNumber = new StringBuilder().append(StringUtils.substring(hardwareVersionNumberStr, 1, 2))
                .append(StringUtils.substring(hardwareVersionNumberStr, 3, 4))
                .append(StringUtils.substring(hardwareVersionNumberStr, 5, 6))
                .append(StringUtils.substring(hardwareVersionNumberStr, 7, 8)).toString();

        //软件版本号
        String softwareVersionNumberStr = data.substring(data.length() - 16, data.length() - 8);
        String softwareVersionNumber = new StringBuilder().append(StringUtils.substring(softwareVersionNumberStr, 1, 2))
                .append(StringUtils.substring(softwareVersionNumberStr, 3, 4))
                .append(StringUtils.substring(softwareVersionNumberStr, 5, 6))
                .append(StringUtils.substring(softwareVersionNumberStr, 7, 8)).toString();

        //厂商编码
        String manufacturerCode = data.substring(data.length() - 40, data.length() - 28);

        //wifiMac
        String wifiMac = data.substring(data.length() - 72, data.length() - 60);
        //查询网关
        TblGateway tblGateway1 = tblGatewayMapper.selectOne(Wrappers.<TblGateway>lambdaQuery().eq(TblGateway::getZigbeeMac, gatewayMac));


        if (tblGateway1 == null) {
            String address = getAddressMessageByIp(clientIp, gatewayMac);
            TblGateway tblGateway = TblGateway.builder().zigbeeMac(gatewayMac).wifiMac(wifiMac).hardwareVersionNumber(hardwareVersionNumber)
                    .softwareVersionNumber(softwareVersionNumber).manufacturerCode(manufacturerCode).remoteIp(clientIp)
                    .gatewayAddress(address).gatewayPush("1").build();
            int insert = tblGatewayMapper.insert(tblGateway);
            if (insert < 1) {
                log.info("网关添加失败：gatewayMac{},data{}", gatewayMac, data);
            }
        }
        if (tblGateway1 != null) {
            TblGateway tblGateway = TblGateway.builder().wifiMac(wifiMac).hardwareVersionNumber(hardwareVersionNumber)
                    .softwareVersionNumber(softwareVersionNumber).remoteIp(clientIp)
                    .manufacturerCode(manufacturerCode).build();
            if (!clientIp.equals(tblGateway1.getRemoteIp()) && !StringUtils.startsWith(clientIp, IGNORE_START)) {
                tblGateway.setGatewayAddress(getAddressMessageByIp(clientIp, gatewayMac));
            }
            if (StringUtils.isEmpty(tblGateway1.getGatewayAddress())) {
                tblGateway.setGatewayAddress(getAddressMessageByIp(clientIp, gatewayMac));
            }

            int update = tblGatewayMapper.update(tblGateway, Wrappers.<TblGateway>lambdaQuery()
                    .eq(TblGateway::getZigbeeMac, gatewayMac));
            if (update < 1) {
                log.info("网关数据修改失败：gatewayMac{},data{}", gatewayMac, data);
            }
        }
        return true;
    }

    /**
     * 心跳
     *
     * @return
     */
    public Boolean heartDeal(String gatewayMac, String data, String clientIp) {
        TblGateway gateway = new TblGateway();
        gateway.setRemoteIp(clientIp);
        gateway.setSwitchTime(LocalDateTime.now());
        int update = tblGatewayMapper.update(gateway, Wrappers.<TblGateway>lambdaQuery()
                .eq(TblGateway::getZigbeeMac, gatewayMac));
        if (update < 1) {
            log.warn("网关心跳帧修改数据失败：gatewayMac{},data{}", gatewayMac, data);
        }
        if (update > 0) {
            Map<String, Object> gatewayMessage = new HashMap<>(5);
            gatewayMessage.put("type", "gateway");
            gatewayMessage.put("gatewayMac", gatewayMac);
            gatewayMessage.put("time", LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            mqttDataHandle.basePush(Topic.device.topics + gatewayMac + Topic.gateway, JSONObject.toJSONString(gatewayMessage));
        }
        return true;
    }


    /**
     * 获取IP地址信息
     *
     * @param ip
     * @return
     */
    public static String getAddressMessageByIp(String ip, String gatewayMac) {
        String host = "https://hcapi22.market.alicloudapi.com";
        String path = "/ip";
        String appcode = "abc58fd71d4b472194d0f8c72626041a";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ip", ip);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, headers, querys);
            String addressMessage = EntityUtils.toString(response.getEntity());
            //获取response的body
            return addressMessage;
        } catch (Exception e) {
            log.warn("通过远程ip获取地址信息失败：ip{},gatewayMac{}", ip, gatewayMac);
        }
        return null;
    }
}
